package com.dream.libmp3lame.sample;

import android.content.Context;
import com.dream.libmp3lame.MP3Lame;

public class MP3RecSample {
    private final MP3Lame mLame = new MP3Lame();
    private final String mp3Path;
    public MP3RecSample(Context ct,
                        String mp3Path,
                        int sample,
                        int channel,
                        int bitRate,
                        int quality, boolean isVbr){

        this.mp3Path = mp3Path;
        mLame.initRec(mp3Path,sample,sample,channel,channel,
                bitRate,quality,
                isVbr);
    }

    public void write(byte[] pcm,int size){
        if (size <= 0){
            return;
        }

        short[] shorts = new short[pcm.length/2];
        toShortLittle(pcm,shorts,size,true);

        mLame.writeRec(shorts,size/2);
    }

    public void release(){
        mLame.flushRec();
        mLame.release();
    }


    public static int toShortLittle(byte[] src,short[] des,
                                    int size,boolean isLittle) {

        int count = size/2;

        if (isLittle){
            for (int i = 0; i < count; i++) {
                des[i] =
                        (short) (src[i * 2+1] << 8 | src[2 * i] & 0xff);
            }
        }else {
            for (int i = 0; i < count; i++) {
                des[i] =
                        (short) (src[i * 2] << 8 | src[2 * i+1] & 0xff);
            }
        }

        return count;
    }

}
